﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using System.Collections.Specialized;

// The data model defined by this file serves as a representative example of a strongly-typed
// model that supports notification when members are added, removed, or modified.  The property
// names chosen coincide with data bindings in the standard item templates.
//
// Applications may use this model as a starting point and build on it, or discard it entirely and
// replace it with something appropriate to their needs.

namespace MSHelpMeHD.Data
{
    using System.Globalization;
    using System.Text;
    using System.Xml.Linq;

    using MSHelpMeHD.BingService;

    /// <summary>
    /// Base class for <see cref="SampleDataItem"/> and <see cref="SampleDataGroup"/> that
    /// defines properties common to both.
    /// </summary>
    [Windows.Foundation.Metadata.WebHostHidden]
    public abstract class SampleDataCommon : MSHelpMeHD.Common.BindableBase
    {
        public static Uri _baseUri = new Uri("ms-appx:///");

        public SampleDataCommon(String uniqueId, String title, String subtitle, String imagePath, String summary)
        {
            this._uniqueId = uniqueId;
            this.title = title;
            this._subtitle = subtitle;
            this.summary = summary;
            this._imagePath = imagePath;
        }

        private string _uniqueId = string.Empty;
        public string UniqueId
        {
            get { return this._uniqueId; }
            set { this.SetProperty(ref this._uniqueId, value); }
        }

        private string title = string.Empty;
        public string Title
        {
            get { return this.title; }
            set { this.SetProperty(ref this.title, value); }
        }

        private string _subtitle = string.Empty;
        public string Subtitle
        {
            get { return this._subtitle; }
            set { this.SetProperty(ref this._subtitle, value); }
        }

        private string summary = string.Empty;
        public string Summary
        {
            get { return this.summary; }
            set { this.SetProperty(ref this.summary, value); }
        }

        private ImageSource _image = null;
        private String _imagePath = null;

        public void SetImage(String path)
        {
            this._image = null;
            this._imagePath = path;
            this.OnPropertyChanged("Image");
        }

        public override string ToString()
        {
            return this.Title;
        }
    }

    /// <summary>
    /// Generic item data model.
    /// </summary>
    public class SampleDataItem : SampleDataCommon
    {
        public static Dictionary<string, string> icons = new Dictionary<string, string>();

        public static Dictionary<string, string> bigIcons = new Dictionary<string, string>();

        static SampleDataItem()
        {
            icons.Add("1", "Assets/kb.png");
            icons.Add("2", "Assets/kb.png");
            icons.Add("3", "Assets/kb.png");
            icons.Add("4", "Assets/kb.png");
            icons.Add("5", "Assets/msdn.png");
            icons.Add("6", "Assets/technet.png");
            icons.Add("25", "Assets/office.png");
            icons.Add("26", "Assets/ie2.png");
            icons.Add("27", "Assets/windows.png");
            icons.Add("28", "Assets/windows.png");
            icons.Add("29", "Assets/answers.png");
            icons.Add("30", "Assets/windowsphone.png");
            icons.Add("31", "Assets/xbox.png");
            icons.Add("36", "Assets/office.png");
            icons.Add("37", "Assets/windows.png");

            icons.Add("kb", "Assets/kb.png");
            icons.Add("msdn", "Assets/msdn.png");
            icons.Add("technet", "Assets/technet.png");
            icons.Add("office", "Assets/office.png");
            icons.Add("ie", "Assets/ie2.png");
            icons.Add("windows", "Assets/windows.png");
            icons.Add("answers", "Assets/answers.png");
            icons.Add("wp", "Assets/windowsphone.png");
            icons.Add("xbox", "Assets/xbox.png");

            bigIcons.Add("1", "Assets/kb_big.png");
            bigIcons.Add("2", "Assets/kb_big.png");
            bigIcons.Add("3", "Assets/kb_big.png");
            bigIcons.Add("4", "Assets/kb_big.png");
            bigIcons.Add("5", "Assets/msdn_big.png");
            bigIcons.Add("6", "Assets/technet_big.png");
            bigIcons.Add("25", "Assets/office_big.png");
            bigIcons.Add("26", "Assets/ie2_big.png");
            bigIcons.Add("27", "Assets/windows_big.png");
            bigIcons.Add("28", "Assets/windows_big.png");
            bigIcons.Add("29", "Assets/answers_big.png");
            bigIcons.Add("30", "Assets/windowsphone_big.png");
            bigIcons.Add("31", "Assets/xbox_big.png");
            bigIcons.Add("36", "Assets/office_big.png");
            bigIcons.Add("37", "Assets/windows_big.png");

            bigIcons.Add("kb", "Assets/kb_big.png");
            bigIcons.Add("msdn", "Assets/msdn_big.png");
            bigIcons.Add("technet", "Assets/technet_big.png");
            bigIcons.Add("office", "Assets/office_big.png");
            bigIcons.Add("ie", "Assets/ie2_big.png");
            bigIcons.Add("windows", "Assets/windows_big.png");
            bigIcons.Add("answers", "Assets/answers_big.png");
            bigIcons.Add("wp", "Assets/windowsphone_big.png");
            bigIcons.Add("xbox", "Assets/xbox_big.png");
        }

        public SampleDataItem()
            : this(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, null)
        {

        }

        public SampleDataItem(String uniqueId, String title, String subtitle, String imagePath, String description, String content, SampleDataGroup group)
            : base(uniqueId, title, subtitle, imagePath, description)
        {
            this._content = content;
            this._group = group;
        }

        private string _content = string.Empty;
        public string Content
        {
            get { return this._content; }
            set { this.SetProperty(ref this._content, value); }
        }

        private SampleDataGroup _group;
        public SampleDataGroup Group
        {
            get { return this._group; }
            set { this.SetProperty(ref this._group, value); }
        }

        private string assetType = string.Empty;
        public string AssetType
        {
            get { return this.assetType; }
            set { this.SetProperty(ref this.assetType, value); }
        }

        private string lastModifiedTime = string.Empty;
        public string LastModifiedTime
        {
            get { return this.lastModifiedTime; }
            set { this.SetProperty(ref this.lastModifiedTime, value); }
        }

        private string uri = string.Empty;
        public string Uri
        {
            get { return this.uri; }
            set { this.SetProperty(ref this.uri, value); }
        }

        public bool Flagged
        {
            get
            {
                return SampleDataSource.Instance.HasFlagged(this);
            }
        }

        public string FlaggedIcon
        {
            get
            {
                return SampleDataCommon._baseUri + (this.Flagged ? "Assets/star_2.png" : "Assets/star_1.png");
            }
        }

        public string Icon
        {
            get
            {
                return SampleDataCommon._baseUri + (icons.ContainsKey(this.AssetType) ? icons[this.AssetType] : "Assets/help.png");
            }
        }

        public string BigIcon
        {
            get
            {
                return SampleDataCommon._baseUri + (bigIcons.ContainsKey(this.AssetType) ? bigIcons[this.AssetType] : "Assets/help_big.png");
            }
        }

        public void NotifyFlagChanged()
        {
            base.OnPropertyChanged("Flagged");
            base.OnPropertyChanged("FlaggedIcon");
        }

        public string ToXml()
        {
            var node = new XElement("result");
            node.SetElementValue("title", this.Title);
            node.SetElementValue("summary", this.Summary);
            node.SetElementValue("assetType", this.AssetType);
            node.SetAttributeValue("uri", this.Uri);
            node.SetAttributeValue("modified", this.LastModifiedTime);

            return node.ToString();
        }

        public static SampleDataItem Create(WebResult bingItem)
        {
            var item = new SampleDataItem
            {
                Title = bingItem.Title,
                Summary = bingItem.Description,
                Uri = bingItem.Url,
                AssetType = DetectAssetType(bingItem.Url.ToLowerInvariant()),
                LastModifiedTime = GetLastModTime(bingItem.DateTime)
            };

            return item;
        }

        private static string GetLastModTime(string time)
        {
            var modtime = DateTime.Now;

            if (!string.IsNullOrWhiteSpace(time))
            {
                DateTime.TryParse(time, out modtime);
            }

            return modtime.ToString(CultureInfo.InvariantCulture);
        }

        private static string DetectAssetType(string url)
        {
            if (url.Contains("/kb/"))
            {
                return "kb";
            }

            if (url.Contains("msdn"))
            {
                return "msdn";
            }

            if (url.Contains("technet"))
            {
                return "technet";
            }

            if (url.Contains("office"))
            {
                return "office";
            }

            if (url.Contains("/ie/"))
            {
                return "ie";
            }

            if (url.Contains("windows") || url.Contains("windowsteamblog"))
            {
                return "windows";
            }

            if (url.Contains("windowsphone") || url.Contains("zune"))
            {
                return "wp";
            }

            if (url.Contains("xbox"))
            {
                return "xbox";
            }

            if (url.Contains("answers"))
            {
                return "answers";
            }

            return string.Empty;
        }

        public static SampleDataItem ParseResultElement(XElement element)
        {
            var item = new SampleDataItem();
            var e = element.Element("title");

            if (e != null)
            {
                item.Title = e.Value;
            }

            e = element.Element("summary");

            if (e != null)
            {
                item.Summary = e.Value;
            }

            e = element.Element("assetType");

            if (e != null)
            {
                item.assetType = e.Value;
            }

            var a = element.Attribute("uri");

            if (a != null)
            {
                item.Uri = a.Value;
            }

            a = element.Attribute("modified");

            if (a != null)
            {
                item.LastModifiedTime = GetLastModTime(a.Value);
            }

            return item;
        }
    }

    /// <summary>
    /// Generic group data model.
    /// </summary>
    public class SampleDataGroup : SampleDataCommon
    {
        public SampleDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description)
            : base(uniqueId, title, subtitle, imagePath, description)
        {
            Items.CollectionChanged += ItemsCollectionChanged;
        }

        private void ItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            // Provides a subset of the full items collection to bind to from a GroupedItemsPage
            // for two reasons: GridView will not virtualize large items collections, and it
            // improves the user experience when browsing through groups with large numbers of
            // items.
            //
            // A maximum of 12 items are displayed because it results in filled grid columns
            // whether there are 1, 2, 3, 4, or 6 rows displayed

            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    if (e.NewStartingIndex < 12)
                    {
                        TopItems.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]);
                        if (TopItems.Count > 12)
                        {
                            TopItems.RemoveAt(12);
                        }
                    }
                    break;
                case NotifyCollectionChangedAction.Move:
                    if (e.OldStartingIndex < 12 && e.NewStartingIndex < 12)
                    {
                        TopItems.Move(e.OldStartingIndex, e.NewStartingIndex);
                    }
                    else if (e.OldStartingIndex < 12)
                    {
                        TopItems.RemoveAt(e.OldStartingIndex);
                        TopItems.Add(Items[11]);
                    }
                    else if (e.NewStartingIndex < 12)
                    {
                        TopItems.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]);
                        TopItems.RemoveAt(12);
                    }
                    break;
                case NotifyCollectionChangedAction.Remove:
                    if (e.OldStartingIndex < 12)
                    {
                        TopItems.RemoveAt(e.OldStartingIndex);
                        if (Items.Count >= 12)
                        {
                            TopItems.Add(Items[11]);
                        }
                    }
                    break;
                case NotifyCollectionChangedAction.Replace:
                    if (e.OldStartingIndex < 12)
                    {
                        TopItems[e.OldStartingIndex] = Items[e.OldStartingIndex];
                    }
                    break;
                case NotifyCollectionChangedAction.Reset:
                    TopItems.Clear();
                    while (TopItems.Count < Items.Count && TopItems.Count < 12)
                    {
                        TopItems.Add(Items[TopItems.Count]);
                    }
                    break;
            }
        }

        private ObservableCollection<SampleDataItem> _items = new ObservableCollection<SampleDataItem>();
        public ObservableCollection<SampleDataItem> Items
        {
            get { return this._items; }
        }

        private ObservableCollection<SampleDataItem> _topItem = new ObservableCollection<SampleDataItem>();
        public ObservableCollection<SampleDataItem> TopItems
        {
            get { return this._topItem; }
        }
    }

    /// <summary>
    /// Creates a collection of groups and items with hard-coded content.
    /// 
    /// SampleDataSource initializes with placeholder data rather than live production
    /// data so that sample data is provided at both design-time and run-time.
    /// </summary>
    public sealed class SampleDataSource : MSHelpMeHD.Common.BindableBase
    {
        private const int MaxFlaggedItem = 1000;

        private readonly Dictionary<string, SampleDataItem> uriCheckes;

        private static SampleDataSource instance = new SampleDataSource();

        private ObservableCollection<SampleDataGroup> _allGroups = new ObservableCollection<SampleDataGroup>();

        public ObservableCollection<SampleDataGroup> AllGroups
        {
            get { return this._allGroups; }
        }

        public static IEnumerable<SampleDataGroup> GetGroups(string uniqueId)
        {
            if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");

            return instance.AllGroups;
        }

        public static SampleDataGroup GetGroup(string uniqueId)
        {
            // Simple linear search is acceptable for small data sets
            var matches = instance.AllGroups.Where((group) => group.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public static SampleDataItem GetItem(string uniqueId)
        {
            // Simple linear search is acceptable for small data sets
            var matches = instance.AllGroups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public static SampleDataItem GetFlaggeditem(string url)
        {
            var matches = instance.FlaggedItems.Where(i => i.Uri == url);
            if (matches.Count() >= 1) return matches.First();
            return null;
        }

        public static SampleDataSource Instance
        {
            get
            {
                return instance;
            }
        }

        public ObservableCollection<SampleDataItem> Items { get; private set; }

        public ObservableCollection<SampleDataItem> FlaggedItems { get; private set; }

        private string queryText = string.Empty;
        public string QueryText
        {
            get { return this.queryText; }
            set { this.SetProperty(ref this.queryText, value); }
        }

        private uint totalFound;
        public uint TotalFound
        {
            get { return this.totalFound; }
            set { this.SetProperty(ref this.totalFound, value); }
        }

        private bool notVoted = true;
        public bool NotVoted
        {
            get { return this.notVoted; }
            set { this.SetProperty(ref this.notVoted, value); }
        }

        protected uint totalSearched;
        public uint TotalSearched
        {
            get { return this.totalSearched; }
            set { this.SetProperty(ref this.totalSearched, value); }
        }

        public int LeftCount
        {
            get
            {
                return MaxFlaggedItem - this.FlaggedItems.Count;
            }
        }

        public int FlaggedCount
        {
            get
            {
                return this.FlaggedItems.Count;
            }
        }

        public int MaxFlaggedItemCount
        {
            get
            {
                return MaxFlaggedItem;
            }
        }

        public SampleDataSource()
        {
            this.Items = new ObservableCollection<SampleDataItem>();
            this.FlaggedItems = new ObservableCollection<SampleDataItem>();
            this.uriCheckes = new Dictionary<string, SampleDataItem>();

            #region Hardcode Data

            String ITEM_CONTENT = String.Format("Item Content: {0}\n\n{0}\n\n{0}\n\n{0}\n\n{0}\n\n{0}\n\n{0}",
                        "Curabitur class aliquam vestibulum nam curae maecenas sed integer cras phasellus suspendisse quisque donec dis praesent accumsan bibendum pellentesque condimentum adipiscing etiam consequat vivamus dictumst aliquam duis convallis scelerisque est parturient ullamcorper aliquet fusce suspendisse nunc hac eleifend amet blandit facilisi condimentum commodo scelerisque faucibus aenean ullamcorper ante mauris dignissim consectetuer nullam lorem vestibulum habitant conubia elementum pellentesque morbi facilisis arcu sollicitudin diam cubilia aptent vestibulum auctor eget dapibus pellentesque inceptos leo egestas interdum nulla consectetuer suspendisse adipiscing pellentesque proin lobortis sollicitudin augue elit mus congue fermentum parturient fringilla euismod feugiat");

            var group1 = new SampleDataGroup("Group-1",
                    "Group Title: 1",
                    "Group Subtitle: 1",
                    "Assets/DarkGray.png",
                    "Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
            group1.Items.Add(new SampleDataItem("Group-1-Item-1",
                    "Item Title: 1",
                    "Item Subtitle: 1",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group1));
            group1.Items.Add(new SampleDataItem("Group-1-Item-2",
                    "Item Title: 2",
                    "Item Subtitle: 2",
                    "Assets/DarkGray.png",
                    "Item Description",
                    ITEM_CONTENT,
                    group1));
            group1.Items.Add(new SampleDataItem("Group-1-Item-3",
                    "Item Title: 3",
                    "Item Subtitle: 3",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group1));
            group1.Items.Add(new SampleDataItem("Group-1-Item-4",
                    "Item Title: 4",
                    "Item Subtitle: 4",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group1));
            group1.Items.Add(new SampleDataItem("Group-1-Item-5",
                    "Item Title: 5",
                    "Item Subtitle: 5",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group1));
            this.AllGroups.Add(group1);

            var group2 = new SampleDataGroup("Group-2",
                    "Group Title: 2",
                    "Group Subtitle: 2",
                    "Assets/LightGray.png",
                    "Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
            group2.Items.Add(new SampleDataItem("Group-2-Item-1",
                    "Item Title: 1",
                    "Item Subtitle: 1",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group2));
            group2.Items.Add(new SampleDataItem("Group-2-Item-2",
                    "Item Title: 2",
                    "Item Subtitle: 2",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group2));
            group2.Items.Add(new SampleDataItem("Group-2-Item-3",
                    "Item Title: 3",
                    "Item Subtitle: 3",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group2));
            this.AllGroups.Add(group2);

            var group3 = new SampleDataGroup("Group-3",
                    "Group Title: 3",
                    "Group Subtitle: 3",
                    "Assets/MediumGray.png",
                    "Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
            group3.Items.Add(new SampleDataItem("Group-3-Item-1",
                    "Item Title: 1",
                    "Item Subtitle: 1",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            group3.Items.Add(new SampleDataItem("Group-3-Item-2",
                    "Item Title: 2",
                    "Item Subtitle: 2",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            group3.Items.Add(new SampleDataItem("Group-3-Item-3",
                    "Item Title: 3",
                    "Item Subtitle: 3",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            group3.Items.Add(new SampleDataItem("Group-3-Item-4",
                    "Item Title: 4",
                    "Item Subtitle: 4",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            group3.Items.Add(new SampleDataItem("Group-3-Item-5",
                    "Item Title: 5",
                    "Item Subtitle: 5",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            group3.Items.Add(new SampleDataItem("Group-3-Item-6",
                    "Item Title: 6",
                    "Item Subtitle: 6",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            group3.Items.Add(new SampleDataItem("Group-3-Item-7",
                    "Item Title: 7",
                    "Item Subtitle: 7",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group3));
            this.AllGroups.Add(group3);

            var group4 = new SampleDataGroup("Group-4",
                    "Group Title: 4",
                    "Group Subtitle: 4",
                    "Assets/LightGray.png",
                    "Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
            group4.Items.Add(new SampleDataItem("Group-4-Item-1",
                    "Item Title: 1",
                    "Item Subtitle: 1",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group4));
            group4.Items.Add(new SampleDataItem("Group-4-Item-2",
                    "Item Title: 2",
                    "Item Subtitle: 2",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group4));
            group4.Items.Add(new SampleDataItem("Group-4-Item-3",
                    "Item Title: 3",
                    "Item Subtitle: 3",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group4));
            group4.Items.Add(new SampleDataItem("Group-4-Item-4",
                    "Item Title: 4",
                    "Item Subtitle: 4",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group4));
            group4.Items.Add(new SampleDataItem("Group-4-Item-5",
                    "Item Title: 5",
                    "Item Subtitle: 5",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group4));
            group4.Items.Add(new SampleDataItem("Group-4-Item-6",
                    "Item Title: 6",
                    "Item Subtitle: 6",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group4));
            this.AllGroups.Add(group4);

            var group5 = new SampleDataGroup("Group-5",
                    "Group Title: 5",
                    "Group Subtitle: 5",
                    "Assets/MediumGray.png",
                    "Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
            group5.Items.Add(new SampleDataItem("Group-5-Item-1",
                    "Item Title: 1",
                    "Item Subtitle: 1",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group5));
            group5.Items.Add(new SampleDataItem("Group-5-Item-2",
                    "Item Title: 2",
                    "Item Subtitle: 2",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group5));
            group5.Items.Add(new SampleDataItem("Group-5-Item-3",
                    "Item Title: 3",
                    "Item Subtitle: 3",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group5));
            group5.Items.Add(new SampleDataItem("Group-5-Item-4",
                    "Item Title: 4",
                    "Item Subtitle: 4",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group5));
            this.AllGroups.Add(group5);

            var group6 = new SampleDataGroup("Group-6",
                    "Group Title: 6",
                    "Group Subtitle: 6",
                    "Assets/DarkGray.png",
                    "Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
            group6.Items.Add(new SampleDataItem("Group-6-Item-1",
                    "Item Title: 1",
                    "Item Subtitle: 1",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-2",
                    "Item Title: 2",
                    "Item Subtitle: 2",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-3",
                    "Item Title: 3",
                    "Item Subtitle: 3",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-4",
                    "Item Title: 4",
                    "Item Subtitle: 4",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-5",
                    "Item Title: 5",
                    "Item Subtitle: 5",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-6",
                    "Item Title: 6",
                    "Item Subtitle: 6",
                    "Assets/MediumGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-7",
                    "Item Title: 7",
                    "Item Subtitle: 7",
                    "Assets/DarkGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            group6.Items.Add(new SampleDataItem("Group-6-Item-8",
                    "Item Title: 8",
                    "Item Subtitle: 8",
                    "Assets/LightGray.png",
                    "Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
                    ITEM_CONTENT,
                    group6));
            this.AllGroups.Add(group6);

            #endregion
        }

        public void LoadData(string data)
        {
            // Load flagged items
            var doc = XDocument.Parse(data);

            if (doc.Root != null)
            {
                var flaggedNode = doc.Root.Element("flagged");

                if (flaggedNode != null)
                {
                    var nodes = from i in flaggedNode.Elements("result")
                                select i;

                    foreach (var node in nodes)
                    {
                        this.FlagItem(SampleDataItem.ParseResultElement(node));
                    }
                }

                var votedNode = doc.Root.Element("notvoted");

                if (votedNode != null)
                {
                    this.NotVoted = bool.Parse(votedNode.Value);
                }

                var totalSearchedNode = doc.Root.Element("searched");

                if (totalSearchedNode != null)
                {
                    this.TotalSearched = uint.Parse(totalSearchedNode.Value);
                }
            }
        }

        public string ToXml()
        {
            var sb = new StringBuilder();
            sb.Append("<root>");
            sb.AppendFormat("<notvoted>{0}</notvoted>", this.NotVoted);
            sb.AppendFormat("<searched>{0}</searched>", this.TotalSearched);

            sb.Append("<flagged>");

            foreach (var i in this.FlaggedItems)
            {
                sb.Append(i.ToXml());
            }

            sb.Append("</flagged>");
            sb.Append("</root>");

            return sb.ToString();
        }

        public void ClearSearchResults()
        {
            SampleDataSource.instance.Items.Clear();
            SampleDataSource.instance.TotalFound = 0;
        }

        public bool AppendSearchResult(SearchResponse results)
        {
            this.TotalFound = 0;

            if (results == null)
            {
                return false;
            }

            if (results.Web == null)
            {
                return false;
            }

            this.TotalFound = results.Web.Total;

            if (this.totalFound == 0 || results.Web.Results == null)
            {
                return false;
            }

            var nodes = from i in results.Web.Results
                        select i;

            foreach (var node in nodes)
            {
                this.Items.Add(SampleDataItem.Create(node));
            }

            return true;
        }

        public void FlagItem(SampleDataItem item)
        {
            if (item.Flagged)
            {
                UnflagItem(item);
                return;
            }

            if (this.FlaggedItems.Count > MaxFlaggedItem)
            {
                return;
            }

            this.uriCheckes.Add(item.Uri, item);
            this.FlaggedItems.Add(item);

            this.NotifyItems(item.Uri);
            this.OnPropertyChanged("LeftCount");
            this.OnPropertyChanged("FlaggedCount");
        }

        public void UnflagItem(SampleDataItem item)
        {
            var flagged = this.uriCheckes[item.Uri];

            this.FlaggedItems.Remove(flagged);
            this.uriCheckes.Remove(flagged.Uri);

            flagged.NotifyFlagChanged();

            this.NotifyItems(flagged.Uri);
            this.OnPropertyChanged("LeftCount");
            this.OnPropertyChanged("FlaggedCount");
        }

        private void NotifyItems(string uri)
        {
            foreach (var i in this.Items.Where(i => i.Uri == uri))
            {
                i.NotifyFlagChanged();
            }
        }

        public bool HasFlagged(SampleDataItem item)
        {
            return this.uriCheckes.ContainsKey(item.Uri);
        }
    }
}
